package ut.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.ByteArrayOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
public class HttpClient{
	public static String sendHttpRequest(String source, String args, boolean isPost){
		URL url = null;
		try{
			if(isPost){
				url = new URL(source);
			}else{
				url = new URL(source + "?" + args);
			}
		}catch(MalformedURLException e){
			e.printStackTrace();
			return null;
		}

		HttpURLConnection con = null;
		OutputStreamWriter writer = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		try{
			con = (HttpURLConnection)url.openConnection();
			if(isPost){
				con.setDoOutput(true);
				con.setRequestMethod("POST");
				writer = new OutputStreamWriter(con.getOutputStream());
				writer.write(args);
				writer.close();
			}
			if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
				in = con.getInputStream();
				out = new ByteArrayOutputStream();
				byte[] buffer = new byte[512];
				int len;
				while((len = in.read(buffer)) > -1){
					out.write(buffer, 0, len);
				}
				String encoding = con.getContentEncoding();
				if(encoding == null){
					encoding = "utf-8";
				}
				return out.toString(encoding);
			}else{
				return null;
			}
		}catch(IOException e){
			e.printStackTrace();
			return null;
		}finally{
			try{
				if(writer != null){
					writer.close();
				}
				if(in != null){
					in.close();
				}
				if(out != null){
					out.close();
				}
			}catch(IOException e){
				e.printStackTrace();
				return null;
			}
		}
	}
}